package com.ddogring.web.controller.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddogring.business.domain.Commodity;
import com.ddogring.business.service.ICommodityService;
import com.ddogring.common.constant.Constants;
import com.ddogring.common.core.controller.BaseController;
import com.ddogring.common.core.domain.AjaxResult;
import com.ddogring.common.core.domain.entity.SysUser;
import com.ddogring.common.core.redis.RedisCache;
import com.ddogring.common.utils.StringUtils;
import com.ddogring.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: eshop
 * @BelongsPackage: com.ddogring.web.controller.business
 * @Author: DdogRing
 * @CreateTime: 2023-01-31  14:36
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController extends BaseController {

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;



    /**
     * @description: 餐品列表查询
     * @author: DdogRing
     * @date: 2023/1/31 15:00
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/list")
    public AjaxResult commodityList(@RequestBody Commodity commodity) {
        if (null == commodity.pageNum()) {
            commodity.setPageNum(1);
        }
        if (null == commodity.pageSize()) {
            commodity.setPageSize(12);
        }
        Page<Commodity> page = new Page<>(commodity.pageNum(), commodity.pageSize());
        commodity.setDelFlag(0);
        commodity.setStatus(2);
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();queryWrapper.like(null != commodity.getCommodity() && !"".equals(commodity.getCommodity()), "commodity", commodity.getCommodity());
        page = commodityService.page(page, queryWrapper);
        return getPage(page, Commodity.class);
    }

    /**
     * @description: 餐品详情查询
     * @author: DdogRing
     * @date: 2023/1/31 15:00
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/info")
    public AjaxResult commodityInfo(@RequestBody Commodity commodity) {
        if (null == commodity || null == commodity.getId()) {
            return AjaxResult.error("餐品不存在");
        }
        return AjaxResult.success(commodityService.getCommodityInfo(commodity.getId()));
    }

    /**
     * @description: 餐品发布
     * @author: DdogRing
     * @date: 2023/1/31 15:02
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/listProducts")
    public AjaxResult listProducts(@Valid @RequestBody Commodity commodity) {
        if (null == commodity.getStatus()) {
            commodity.setStatus(2);
        }
        // 不包邮必须给邮费
        if (1 == commodity.getIsMail() && null == commodity.getMailPrice()) {
            return AjaxResult.success("请输入邮费");
        }

        if (null == commodity.getUserId()) {
            commodity.setUserId(getLoginUser().getUserId().intValue());
        }

        commodity.setRemainder(commodity.getTotal());
        return toAjax(commodityService.save(commodity));
    }

    /**
     * @description: 购物车添加
     * @author: DdogRing
     * @date: 2023/2/7 17:11
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/shoppingCart")
    public AjaxResult shoppingCart(@RequestBody Commodity commodity) {
        List<Commodity> cacheList = redisCache.getCacheList(Constants.SHOPPING_CART + getLoginUser().getUserId());
        if (null == cacheList || cacheList.size() == 0) {
            cacheList = new ArrayList<>();
            cacheList.add(commodity);
        } else {
            Integer id = commodity.getId();
            boolean flag = false;
            for (Commodity c:cacheList) {
                if (c.getId().equals(id)) {
                    c.setAddNumber(c.getAddNumber() + commodity.getAddNumber());
                    flag = true;
                }
            }

            if (!flag) {
                cacheList.add(commodity);
            }
        }

        redisCache.deleteObject(Constants.SHOPPING_CART + getLoginUser().getUserId());
        redisCache.setCacheList(Constants.SHOPPING_CART + getLoginUser().getUserId(), cacheList);
        return AjaxResult.success();
    }

    /**
     * @description: 购物车删除
     * @author: DdogRing
     * @date: 2023/2/9 09:25
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/removeShoppingCart")
    public AjaxResult removeShoppingCart(@RequestBody Commodity commodity) {
        List<Commodity> cacheList = redisCache.getCacheList(Constants.SHOPPING_CART + getLoginUser().getUserId());
        if (cacheList != null && cacheList.size() > 0) {

            for (int i = cacheList.size() - 1; i >= 0; i--) {
                if (cacheList.get(i).getId().equals(commodity.getId())) {
                    cacheList.remove(cacheList.get(i));
                }
            }
        }
        redisCache.deleteObject(Constants.SHOPPING_CART + getLoginUser().getUserId());

        if (cacheList != null && cacheList.size() > 0) {
            redisCache.setCacheList(Constants.SHOPPING_CART + getLoginUser().getUserId(), cacheList);
        }
        return AjaxResult.success();
    }

    /**
     * @description: 清空购物车
     * @author: DdogRing
     * @date: 2023/2/9 09:37
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @GetMapping("/clearShoppingCart")
    public AjaxResult clearShoppingCart() {
        redisCache.deleteObject(Constants.SHOPPING_CART + getLoginUser().getUserId());
        return AjaxResult.success();
    }

    /**
     * @description: 购物车列表
     * @author: DdogRing
     * @date: 2023/2/7 17:11
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @GetMapping("/shoppingCartList")
    public AjaxResult shoppingCartList() {
        List<Object> cacheList = redisCache.getCacheList(Constants.SHOPPING_CART + getLoginUser().getUserId());
        return AjaxResult.success(cacheList);
    }

    /**
     * @description: 餐品管理查询
     * @author: DdogRing
     * @date: 2023/2/9 10:46
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/merchandiseManagement")
    public AjaxResult merchandiseManagement(@RequestBody Commodity commodity) {
        if (null == commodity.pageNum()) {
            commodity.setPageNum(1);
        }
        if (null == commodity.pageSize()) {
            commodity.setPageSize(10);
        }
        Page<Commodity> page = new Page<>(commodity.pageNum(), commodity.pageSize());
        QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();
        Long userId = getLoginUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser != null) {
            queryWrapper.eq("user_id", sysUser.getShopUserId());
        }
        queryWrapper.eq("del_flag", 0);

        queryWrapper.like(null != commodity.getCommodity() && !"".equals(commodity.getCommodity()), "commodity", commodity.getCommodity());
        queryWrapper.eq(commodity.getStatus() != null, "status", commodity.getStatus());
        queryWrapper.eq(commodity.getIsMail() != null, "isMail", commodity.getIsMail());
        Page<Commodity> page1 = commodityService.page(page, queryWrapper);
        return getPage(page1, Commodity.class);
    }

    /**
     * @description: 餐品修改
     * @author: DdogRing
     * @date: 2023/2/9 10:46
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/editCommodity")
    public AjaxResult editCommodity(@RequestBody Commodity commodity) {

        if (null == commodity || null == commodity.getId()) {
            return AjaxResult.error("餐品不存在");
        }

        Long userId = getLoginUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (null == sysUser || null == sysUser.getShopUserId()) {
            return AjaxResult.error("这不是您的餐品");
        }

        commodity.setUserId(sysUser.getShopUserId().intValue());
        int i = commodityService.editCommodity(commodity);
        return toAjax(i);
    }

    /**
     * @description: 餐品删除
     * @author: DdogRing
     * @date: 2023/2/9 10:59
     * @param: [commodity]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/takeDown")
    public AjaxResult takeDown(@RequestBody Commodity commodity) {
        if (null == commodity || null == commodity.getId()) {
            return AjaxResult.error("餐品不存在");
        }

        Long userId = getLoginUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (null == sysUser || null == sysUser.getShopUserId()) {
            return AjaxResult.error("这不是您的餐品");
        }

        UpdateWrapper<Commodity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", commodity.getId());
        updateWrapper.eq("user_id", sysUser.getShopUserId());
        updateWrapper.set("del_flag", 1);

        commodityService.editCommodity(commodity);
        return AjaxResult.success();
    }
}
